# 菜品信息管理
from django.shortcuts import render
from django.http import HttpResponse

from datetime import datetime
import time, os

from myadmin.models import Product, Category, Shop
from ..utils import get_page


def index(request, pIndex=1):
    mywhere = []
    cid = request.GET.get("category_id", None)
    plists = Product.objects.filter(status__lt=9).filter(category_id=cid)
    if plists:
        mywhere.append('category_id=' + cid)

        kw = request.GET.get("keyword", None)
        if kw:
            plists = plists.filter(name__contains=kw)
            mywhere.append('keyword=' + kw)

        plists = plists.order_by('id')
        list2, plist, pIndex, maxpages = get_page(plists, pIndex, 10)
        # 遍历当前菜品信息并封装对应的店铺和菜品类别信息
        for vo in list2:
            sob = Shop.objects.get(id=vo.shop_id)
            vo.shopname = sob.name
            cob = Category.objects.get(id=vo.category_id)
            vo.categoryname = cob.name
        context = {"productlist": list2, 'plist': plist, 'pIndex': pIndex, 'mywhere': mywhere, 'cid': cid}
    else:
        context = {"productlist": None, 'plist': None, 'pIndex': pIndex, "cid": cid}
    return render(request, "myadmin/product/index.html", context)


def add(request, cid):
    category = Category.objects.get(id=cid)
    shop = Shop.objects.get(id=category.shop_id)
    category.shop_name = shop.name
    context = {"category": category}
    return render(request, "myadmin/product/add.html", context)


def insert(request):
    try:
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            return HttpResponse("没有封面上传文件信息")
        cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
        destination = open("./static/uploads/product/" + cover_pic, "wb+")
        for chunk in myfile.chunks():
            destination.write(chunk)
        destination.close()

        ob = Product()
        ob.shop_id = request.POST['shop_id']
        ob.category_id = request.POST['category_id']
        ob.name = request.POST['name']
        ob.price = request.POST['price']
        ob.cover_pic = cover_pic
        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "添加成功！"}
    except Exception:
        context = {'info': "添加失败！"}
    return render(request, "myadmin/info.html", context)


def delete(request, pid=0):
    try:
        ob = Product.objects.get(id=pid)
        ob.status = 9
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "删除成功！"}
    except Exception:
        context = {'info': "删除失败！"}
    return render(request, "myadmin/info.html", context)


def edit(request, pid=0):
    try:
        ob = Product.objects.get(id=pid)
        shop = Shop.objects.get(id=ob.shop_id)
        ob.shop_name = shop.name
        category = Category.objects.get(id=ob.category_id)
        ob.category_name = category.name
        context = {'product': ob}
        return render(request, "myadmin/product/edit.html", context)
    except Exception:
        context = {'info': "没有找到要修改的信息！"}
        return render(request, "myadmin/info.html", context)


def update(request, pid):
    try:
        oldpicname = request.POST['oldpicname']
        myfile = request.FILES.get("cover_pic", None)
        if not myfile:
            cover_pic = oldpicname
        else:
            cover_pic = str(time.time()) + "." + myfile.name.split('.').pop()
            destination = open("./static/uploads/product/" + cover_pic, "wb+")
            for chunk in myfile.chunks():
                destination.write(chunk)
            destination.close()

        ob = Product.objects.get(id=pid)
        ob.shop_id = request.POST['shop_id']
        ob.category_id = request.POST['category_id']
        ob.name = request.POST['name']
        ob.price = request.POST['price']
        ob.cover_pic = cover_pic
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        context = {'info': "修改成功！"}

        # 判断并删除老图片
        if myfile:
            os.remove("./static/uploads/product/" + oldpicname)

    except Exception:
        context = {'info': "修改失败！"}

    return render(request, "myadmin/info.html", context)
